package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.letv.whatslive.common.utils.Constants;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.Employee;
import com.letv.whatslive.model.WeidianItem;
import com.letv.whatslive.model.WeidianUserItems;
import com.letv.whatslive.model.convert.EmployeeConvert;
import com.letv.whatslive.model.convert.WeidianItemConvert;
import com.letv.whatslive.model.convert.WeidianUserItemsConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by wangjian7 on 2016/9/20.
 */
@Repository
public class WeidianUserItemsDAO extends BaseDAO {
    protected String collectionName = "weidianUserItems";
    private final static Logger logger = LoggerFactory.getLogger(WeiDianTokenInfoDAO.class);

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);

    }
    public void updateUserItem(WeidianUserItems weidianUserItems) {
        DBObject queryCondition = new BasicDBObject();
        Long weidianItemId = weidianUserItems.getId();
        queryCondition.put("_id", weidianItemId); // 用来确定要修改的文档
        DBObject setValue = WeidianUserItemsConvert.castWeidianUserItemsToDBObject(weidianUserItems);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }
    public Long countUserItemNum(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }
    public List<WeidianUserItems> getUserItemsByParams(Map params, Integer start, Integer limit){
        List<WeidianUserItems> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBObject order = new BasicDBObject();
            order.put("createTime", -1);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianUserItems weidianUserItems = WeidianUserItemsConvert.castDBObjectToWeidianUserItems(dbObject);
                result.add(weidianUserItems);
            }
        } catch (Exception e) {
            logger.error("getWeidianItemListByParams error!", e);
        }
        return result;
    }


    public void insertItems(List<WeidianUserItems> weidianUserItemsList){
        if(weidianUserItemsList!=null&&weidianUserItemsList.size()>0){
            List<DBObject> dbList = Lists.newArrayList();
            Long createTime = System.currentTimeMillis();
            for(WeidianUserItems weidianUserItems:weidianUserItemsList){
                DBObject dbObject = WeidianUserItemsConvert.castWeidianUserItemsToDBObject(weidianUserItems);
                dbList.add(dbObject);
            }
            this.multiInsert(dbList);
        }
    }

    public void batchUpdateItemStatus(List<String> itemids, int recomend){
        BasicDBObject query = new BasicDBObject();
        BasicDBList values = new BasicDBList();
        if (itemids != null && itemids.size() > 0) {
            for (String itemid : itemids) {
                values.add(itemid);
            }
            query.put("itemid", new BasicDBObject("$in", values));
        }
        DBObject update = new BasicDBObject();
        update.put("recomend", recomend);
        WriteResult result = this.dbCollection.updateMulti(query, new BasicDBObject("$set", update));

    }


    /**
     * 分页查询
     * @param pageNo
     * @param pageSize
     * @param params
     */
    public List<WeidianUserItems> queryByParamWithPages(int pageNo, int pageSize, Map<String, Object> params, DBObject orders){
        List<WeidianUserItems> result = Lists.newArrayList();
        try {
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query).skip((pageNo - 1) * pageSize).sort(orders).limit(pageSize);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianUserItems weidianUserItems = WeidianUserItemsConvert.castDBObjectToWeidianUserItems(dbObject);
                result.add(weidianUserItems);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    public void deleteAllUserItemsByParams(Map<String, Object> params){
        BasicDBObject query = getBasicDBObjectByParams(params);// 新建查询基类对象 dbo
        List<DBObject> result = this.selectAll(query, new BasicDBObject());
        if(result.size()>0){
            for(DBObject dbObject:result){
                BasicDBObject deleteParams = new BasicDBObject();
                deleteParams.put("userId", dbObject.get("userId"));
                deleteParams.put("itemid", dbObject.get("itemid"));
                this.delete(deleteParams);
            }
        }

    }

    public List<WeidianUserItems> getAllWeidianUserItems(Map<String, Object> params, Map<String, Object> orders){
        List<WeidianUserItems> result = Lists.newArrayList();
        try {
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianUserItems weidianUserItems = WeidianUserItemsConvert.castDBObjectToWeidianUserItems(dbObject);
                result.add(weidianUserItems);
            }
        } catch (Exception e) {
            logger.error("getAllWeidianUserItems error!", e);
        }
        return result;

    }

    public Map<String, WeidianUserItems> getWeidianUserItemsMapByUserIdAndOpenId(Long userId, String openid){
        Map<String, WeidianUserItems> result = Maps.newHashMap();
        try {
            BasicDBObject query = new BasicDBObject();
            query.put("userId", userId);
            query.put("openid", openid);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                WeidianUserItems weidianUserItems = WeidianUserItemsConvert.castDBObjectToWeidianUserItems(dbObject);
                result.put(weidianUserItems.getOpenid(), weidianUserItems);
            }
        } catch (Exception e) {
            logger.error("getAllWeidianUserItems error!", e);
        }
        return result;

    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map<String, Object> params){
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {

            if (params.get("id") != null) {
                query.put("_id", ObjectUtils.toString(params.get("id")));
            }

            if (params.get("userId") != null) {
                query.put("userId", ObjectUtils.toLong(params.get("userId")));
            }
            if (params.get("openid") != null) {
                query.put("openid", ObjectUtils.toString(params.get("openid")));
            }
            if (params.get("itemid") != null) {
                query.put("itemid", ObjectUtils.toString(params.get("itemid")));
            }
            if (params.get("recomend") != null) {
                query.put("recomend", ObjectUtils.toInteger(params.get("recomend")));
            }
            if (params.get("priority") != null) {
                query.put("priority", ObjectUtils.toInteger(params.get("priority")));
            }
        }
        return query;
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("_id", -1);
        }
        return order;
    }


}